﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.Web.Mvc;
using eCRAM.WebSite.Attributes;
using eCRAM.WebSite.Models;
using eCRAM.Bll;
using eCRAM.Model;
using eCRAM.WebSite.Services;
using eCRAM.WebSite.Tools;

namespace eCRAM.WebSite.Controllers
{

    [HandleError]
    //[CustomAuthorization(UserRole.ProjectLeader, UserRole.Administrator, UserRole.Engineer, UserRole.SubContractor)]
    public class AccountController : Controller
    {

        [HttpGet]
        public ActionResult LogOn()
        {
            return View();
        }

        /// <summary>
        /// Called when the user entered its username and password.
        /// </summary>
        /// <param name="userName">Login</param>
        /// <param name="password">Password</param>
        /// <returns></returns>
        [HttpPost]
        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Justification = "Needs to take same parameter type as Controller.Redirect()")]
        public ActionResult LogOn(string userName, string password)
        {
            if (!ValidateLogOn(userName, password))
            {
                return View();
            }

            FormsAuthenticationService.SignIn(userName, false);
            return RedirectToAction("Index", "Cram");
        }



        /// <summary>
        /// Checks the username and password are correct.
        /// </summary>
        /// <param name="userName">Login</param>
        /// <param name="password">Password</param>
        /// <returns>True in case the username and password are valid; false otherwise</returns>
        private bool ValidateLogOn(string userName, string password)
        {
            User currentUser = null;

            if (String.IsNullOrEmpty(userName))
                ModelState.AddModelError("userName", "Vous devez renseigner un nom d'utilisateur.");
            if (String.IsNullOrEmpty(password))
                ModelState.AddModelError("password", "Vous devez renseigner un mot de passe.");
            else
            {
                
                try
                {
                    currentUser = UserManager.ConnectUser(userName, password);
                    if (currentUser == null)
                        ModelState.AddModelError("_FORM", "Le nom d'utilisateur ou le mot de passe est incorrect.");
                    else if (!currentUser.IsActive)
                        ModelState.AddModelError("_FORM", "Votre compte est désactivé.");
                }
                catch (Exception e)
                {
                    ModelState.AddModelError(userName, e.Message);
                }
            }

            //FIXME
            Session["MySessionData"] = new SessionData
            {
                CurrentUser = currentUser
            };

            return ModelState.IsValid;

        }


       
        /// <summary>
        /// Logs off the current user.
        /// </summary>
        /// 
        /// <remarks>
        /// Called by LogOnUserControl.ascx (the view).
        /// </remarks>
        /// 
        /// <returns></returns>
        public ActionResult LogOff()
        {
            FormsAuthenticationService.SignOut();
            SessionTools.User = null;
            return RedirectToAction("LogOn", "Account");
        }
     
    }
}
